import { EventHandler } from "./Common";
export class BaseAnimationPlayer {
    LoopPlayback: boolean = null as any
    readonly AnimationTime: number = null as any
    CurrentTime: number = null as any
    CurrentTimeChanged: EventHandler = null as any
    Start: () => void = null as any
    Stop: () => void = null as any
}
export class AnimationPlayer implements BaseAnimationPlayer {
    LoopPlayback = false;
    CurrentTimeChanged = new EventHandler();
    AnimationTime = 0;
    get CurrentTime() {
        return this._CurrentTime;
    }
    set CurrentTime(value: number) {
        this._CurrentTime = value;
        this.CurrentTimeChanged.dispatchEvent();
    }
    private _CurrentTime = 0;
    private _state: {
        clock: THREE.Clock,
        stop: boolean,
        rafHandle: number,
    } = null!;


    Start() {
        if (!this._state) {
            this._state = {
                stop: false,
                clock: new THREE.Clock(true),
                rafHandle: requestAnimationFrame(() => this.render())
            }
        }
        else if (this._state.stop) {
            this._state.stop = false;
            this._state.clock.start();
            this._state.rafHandle = requestAnimationFrame(() => this.render());
        }
    }
    Stop() {
        if (this._state && !this._state.stop) {
            this._state.stop = true;
            this._state.clock.stop();
            cancelAnimationFrame(this._state.rafHandle);
        }
    }

    private render() {
        if (this._state.stop)
            return;
        let deltaTimeMs = this._state.clock.getDelta() * 1000;
        let currentTime = this._CurrentTime + deltaTimeMs;
        if (currentTime > this.AnimationTime) {
            if (this.LoopPlayback) {
                this.CurrentTime = currentTime - this.AnimationTime;
                this._state.rafHandle = requestAnimationFrame(() => this.render());
            }
            else {
                this.Stop();
                this.CurrentTime = 0;
            }
        }
        else {
            this.CurrentTime = currentTime;
            this._state.rafHandle = requestAnimationFrame(() => this.render());
        }
    }
}
